package com.wash.shoes.domain.jd;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCreateOrderV1.*;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.preGetWaybillCodes.PreGetWaybillCodesRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonModifyOrderV1.CommonModifyCancelOrderRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonQueryOrderApi.commonGetOrderStatusV1.CommonOrderStatusRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonSubscribeTraceApi.commonSubscribeTraceV1.CommonSubscribeTraceRequest;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.entity.OAuth2Plugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.*;
import com.lop.open.api.sdk.response.ECAP.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.property.JdProperty;
import com.wash.shoes.domain.dto.MtUserAddress;
import com.wash.shoes.domain.dto.ReserveDto;
import com.wash.shoes.entity.JdCallRecordPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.entity.ShopPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.JdCallRecordService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import com.wash.shoes.service.ShopService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;

/**
 * @author lijianguo
 * @Date 17/09/2024
 **/
@Log4j2
@Component
public class JdCreateOrder {

    @Autowired
    JdProperty jdProperty;

    @Autowired
    JdCallRecordService jdCallRecordService;

    @Autowired
    OrderTransportService orderTransportService;

    @Autowired
    OrderService orderService;

    @Autowired
    ShopService shopService;

    //@PostConstruct
    public void init() throws LopException {

        OrderPo orderPo = orderService.getById("202410205793838239");
        ShopPo shopPo = shopService.getById(orderPo.getShopId());
        MtUserAddress shopAddress = new MtUserAddress();
        shopAddress.setReceiverName(shopPo.getShopName());
        shopAddress.setReceiverMobile(shopPo.getPhone());
        StringBuilder fullAddress = new StringBuilder();
        fullAddress.append(shopPo.getProvincesName());
        fullAddress.append(shopPo.getCityName());
        fullAddress.append(shopPo.getCountryName());
        fullAddress.append(shopPo.getAddress());
        shopAddress.setReceiverAddress(fullAddress.toString());
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderIdType(orderPo.getId(), "取鞋");
        MtUserAddress mtUserAddress = JSONObject.parseObject(orderTransportPo.getDeliveryJson(), MtUserAddress.class);
        log.info("====    ===========  ===========");
        OrderTransportPo toUser = process(orderPo, shopAddress, mtUserAddress, "送鞋", System.currentTimeMillis() / 1000 + 3600 * 15);
    }

    /**
     * @author lijianguo
     * @Date 17/09/2024
     * 请输入方法的简介
     **/
    public OrderTransportPo process(OrderPo orderPo, MtUserAddress send, MtUserAddress receiver, String type, Long seconds) throws LopException, RuntimeException {
        Integer orderOrigin = 2;
        if (StringUtils.equals(type, "送鞋")) {
            orderOrigin = 1;
        }

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        // 开始处理订单
        EcapV1OrdersCreateLopRequest request1 = new EcapV1OrdersCreateLopRequest();
        OAuth2Plugin oAuth2Plugin = (OAuth2Plugin) lopPlugin;
        oAuth2Plugin.setOauthLopDn("ECAP");
        request1.addLopPlugin(lopPlugin);
        CommonCreateOrderRequest commonRequest = new CommonCreateOrderRequest();
        commonRequest.setOrderId(orderPo.getOrderNo() + "_" + RandomUtil.randomNumbers(10));
        // 发送人的信息
        Contact senderContact = new Contact();
        senderContact.setName(send.getReceiverName());
        senderContact.setMobile(send.getReceiverMobile());
        senderContact.setFullAddress(send.getReceiverAddress());
        commonRequest.setSenderContact(senderContact);
        // 收人的信息
        Contact receiverContact = new Contact();
        receiverContact.setName(receiver.getReceiverName());
        receiverContact.setMobile(receiver.getReceiverMobile());
        receiverContact.setFullAddress(receiver.getReceiverAddress());
        commonRequest.setReceiverContact(receiverContact);
        //0 快递C2C	个人消费者寄快递服务，C端用户发给C端用户的快递服务
        //1	快递B2C	电商平台的商家（即京东物流的签约商家）发给C端用户的快递服务，或者企业发C端、B端，但重量（泡重比）小于30kg的业务
        //2	C2B	通常是指从C端揽收送往B端，一般简称C2B业务。例如：图书回收、洗护业务、电商平台客户退货发起的逆向业务等业务场景
        //4	快运B2C	电商平台的商家（即京东物流的签约商家）发给C端用户的快运服务，或者企业发C端、B端，但重量（泡重比）大于30kg的业务
        //5	快运C2C	个人消费者寄快运服务，C端用户发给C端用户的快运服务
        commonRequest.setOrderOrigin(orderOrigin);
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());
        // 序号
        CommonProductInfo productsReq = new CommonProductInfo();
        // 京东标快	ed-m-0001	0-C2C；1-B2C；2-C2B
        // 京东特快	ed-m-0002	0-C2C；1-B2C；2-C2B
        productsReq.setProductCode("ed-m-0001");
        commonRequest.setProductsReq(productsReq);
        // 值：1-寄付；2-到付；orderOrigin= 1 或4时，枚举值：1-寄付；2-到付；3-月结
        commonRequest.setSettleType(3);
        // 货品信息
        CommonCargoInfo cargoes = new CommonCargoInfo();
        cargoes.setName("鞋子/衣服");
        // 默认一个包裹就行了
        cargoes.setQuantity(1);
        cargoes.setWeight(BigDecimal.valueOf(1L));
        cargoes.setVolume(BigDecimal.valueOf(10L));
        commonRequest.setCargoes(Collections.singletonList(cargoes));
//        commonRequest.setWaybillCode(jdCode);
        commonRequest.setRemark(jdProperty.getRemark() + ": " + orderPo.getOrderNo());
        // 设置时间
        commonRequest.setPickupStartTime(seconds * 1000L);
        commonRequest.setPickupEndTime((seconds + 3600) * 1000L);
        request1.setRequest(commonRequest);

        // 订阅消息
        HashMap extendProps = new HashMap();
        extendProps.put("autoSubscribe", "1");
        commonRequest.setExtendProps(extendProps);
        if (orderOrigin == 2) {
            // orderOrigin=2时,C to B ，settleType必须是5，并且c2bAddedSettleTypeInfo必填
            //参考文档：https://open.jdl.com/#/open-business-document/api-doc/267/841 这个参数：settleType描述
            commonRequest.setSettleType(5);
            C2BAddedSettleTypeInfo c2BAddedSettleTypeInfo = new C2BAddedSettleTypeInfo();
            c2BAddedSettleTypeInfo.setBasicFreigthSettleType(3);
            c2BAddedSettleTypeInfo.setPackageServiceSettleType(3);
            c2BAddedSettleTypeInfo.setGuaranteeMoneyServiceSettleType(3);
            commonRequest.setC2bAddedSettleTypeInfo(c2BAddedSettleTypeInfo);
            // orderOrigin=2时，「goods」不能为空
            CommonGoodsInfo commonGoodsInfo = new CommonGoodsInfo();
            commonGoodsInfo.setName("鞋子/衣服");
            commonGoodsInfo.setCode("123456789");
            commonGoodsInfo.setQuantity(orderPo.getShoeNum());
            commonGoodsInfo.setCurrencyCode("CNY");
            commonGoodsInfo.setQuantityUnit("双");
            commonRequest.setGoods(Collections.singletonList(commonGoodsInfo));
        } else {
            //设置结算方式，orderOrigin = 1时为B to c 设置结算方式为 3
            //具体可以参考文档：https://open.jdl.com/#/open-business-document/api-doc/267/841  settleType描述
            commonRequest.setSettleType(3);
        }

        EcapV1OrdersCreateLopResponse response1 = client.execute(request1);
        log.info("京东下单订 Request 参数为  {} ", JSONObject.toJSONString(request1));
        log.info("京东下单订 Response 参数为  {} ", JSONObject.toJSONString(response1));
        if (response1.getResult().getCode() != 0) {
            log.error("京东下单订失败,请查看日志");
            throw new WashException(response1.getResult().getMsg());
        }

        // 京东订单发送成功，记录发送日志，记录订单相关的东西
        JdCallRecordPo jdCallRecordPo = new JdCallRecordPo();
        jdCallRecordPo.setWayBillCode(response1.getResult().getData().getWaybillCode());
        jdCallRecordPo.setOrderId(orderPo.getId());
        jdCallRecordPo.setOrderNo(orderPo.getOrderNo());
        jdCallRecordPo.setRequestInfo(JSONObject.toJSONString(request1));
        jdCallRecordPo.setRespondInfo(JSONObject.toJSONString(response1));
        jdCallRecordPo.setRequestId(response1.getResult().getRequestId());
        jdCallRecordService.save(jdCallRecordPo);

        // 记录订单的发送快递的日志
        OrderTransportPo orderTransportPo = new OrderTransportPo();
        orderTransportPo.setShopId(orderPo.getShopId());
        orderTransportPo.setOrderId(orderPo.getId());
        orderTransportPo.setOrderNo(orderPo.getOrderNo());
        orderTransportPo.setOrderOrigin(String.valueOf(orderOrigin));
        orderTransportPo.setType(type);
        orderTransportPo.setWayBillCode(response1.getResult().getData().getWaybillCode());
        orderTransportPo.setOrderCode(response1.getResult().getData().getOrderCode());
        orderTransportPo.setPrice(response1.getResult().getData().getFreightPre().doubleValue());
        orderTransportPo.setPickupPromiseTime(response1.getResult().getData().getPickupPromiseTime());
        orderTransportPo.setDeliveryPromiseTime(response1.getResult().getData().getDeliveryPromiseTime());
        orderTransportPo.setSendName(senderContact.getName());
        orderTransportPo.setSendMobile(senderContact.getMobile());
        orderTransportPo.setSendFullAddress(senderContact.getFullAddress());
        orderTransportPo.setReceiverName(receiverContact.getName());
        orderTransportPo.setReceiverMobile(receiverContact.getMobile());
        orderTransportPo.setReceiverFullAddress(receiverContact.getFullAddress());

        orderTransportPo.setStatus("100");
        // 保存数据
        orderTransportService.save(orderTransportPo);
        log.info("京东下单成功 {}", JSONObject.toJSONString(orderTransportPo));
        // 消息订阅
        return orderTransportPo;
    }

    /**
     * @author lijianguo
     * @Date 18/09/2024
     * jd物流轨迹订阅
     **/
    public void traceSubscribe(OrderTransportPo orderTransportPo) throws LopException {

        EcapV1OrdersTraceSubscribeLopRequest request = new EcapV1OrdersTraceSubscribeLopRequest();
        CommonSubscribeTraceRequest commonRequest = new CommonSubscribeTraceRequest();
        request.setRequest(commonRequest);

        commonRequest.setWaybillCode(orderTransportPo.getWayBillCode());
        commonRequest.setOrderCode(orderTransportPo.getOrderCode());
        commonRequest.setMobile(orderTransportPo.getReceiverMobile().substring(7));
        commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());
        commonRequest.setBusinessUnitCode(jdProperty.getCustomerCode());


        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);
        EcapV1OrdersTraceSubscribeLopResponse response = client.execute(request);

        log.info("京东消息订阅 request 参数为 {} ", JSONObject.toJSONString(request));
        log.info("京东消息订阅 response 参数为 {} ", JSONObject.toJSONString(response));
    }


    // 更新订单
    public void commonModifyOrder(ReserveDto reserveDto) {
        // 物流信息
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderId(reserveDto.getOrderId());

        // 构造参数
        EcapV1OrdersModifyLopRequest request = new EcapV1OrdersModifyLopRequest();
        CommonModifyCancelOrderRequest commonRequest = new CommonModifyCancelOrderRequest();
        request.setRequest(commonRequest);
        com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonModifyOrderV1.Contact senderContact = new com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonModifyOrderV1.Contact();
        senderContact.setName(reserveDto.getReserveName());
        senderContact.setMobile(reserveDto.getReservePhone());
        senderContact.setPhone(reserveDto.getReservePhone());
        senderContact.setFullAddress(reserveDto.getReserveAddress());
        commonRequest.setSenderContact(senderContact);
        commonRequest.setWaybillCode(orderTransportPo.getWayBillCode());
        commonRequest.setOrderCode(orderTransportPo.getOrderCode());
        commonRequest.setOrderOrigin(2);
        commonRequest.setPickupStartTime(reserveDto.getBookStartTime());
        commonRequest.setPickupEndTime(reserveDto.getBookEndTime());
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);

        try {
            EcapV1OrdersModifyLopResponse response = client.execute(request);
            log.info("京东 物流修改信息的 request {}", JSONObject.toJSONString(request));
            log.info("京东 物流修改信息的 response {}", JSONObject.toJSONString(response));
            if (response.getResult().getCode() != 0) {
                log.error("京东下单订失败,请查看日志");
                throw new WashException(response.getResult().getMsg());
            }
            orderTransportPo.setPickupPromiseTime(reserveDto.getBookEndTime());
            orderTransportPo.setSendName(senderContact.getName());
            orderTransportPo.setSendMobile(senderContact.getMobile());
            orderTransportPo.setSendFullAddress(senderContact.getFullAddress());
            orderTransportService.updateById(orderTransportPo);
        } catch (LopException e) {
            throw new RuntimeException(e);
        }
    }


    // 更新订单
    public String orderStatus(String wayBillCode) {
        // 物流信息
        OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(wayBillCode);

        EcapV1OrdersStatusGetLopRequest request = new EcapV1OrdersStatusGetLopRequest();
        CommonOrderStatusRequest commonRequest = new CommonOrderStatusRequest();
        request.setRequest(commonRequest);
        commonRequest.setWaybillCode(wayBillCode);
        commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);

        try {
            EcapV1OrdersStatusGetLopResponse response = client.execute(request);
            log.info("订单状态  request {} ", JSONObject.toJSONString(request));
            log.info("订单状态  response {} ", JSONObject.toJSONString(response));
            return response.getResult().getData().getStatus();
        } catch (LopException e) {
            log.error(e);
        }
        return null;
    }


    public static void main(String[] args) {
        String s = "18382496398";
        String s2 = s.substring(7);
        System.out.println(s2);
    }


}
